﻿<?php
	session_start();
	
	function generateRandomString($length = 10) {
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    $randomString = '';
	    for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, strlen($characters) - 1)];
	    }
	    return $randomString;
	}
	
	include("sendmail.php");

	if(isset($_GET['key']))
	{
		$key = $_GET['key'];
		include ("config.php");
		
		$newpassword = $_POST['password'];
		$md5pw = md5($newpassword);
		
		$stmt = $con->prepare("UPDATE `User` SET `Password` =  '$md5pw',`ResetKey` = NULL WHERE `ResetKey` = '$key'");
		$stmt->bind_param('ss', $md5pw, $key);
		$stmt->execute();
		
		//$result = $stmt->get_result();
		//$row = $result->fetch_assoc();
		
		//$sql = "UPDATE `User` SET `Password` =  '$md5pw',`ResetKey` = NULL WHERE `ResetKey` = '$key'";
		
		//if (!mysqli_query($con,$sql))
		//{
			//die('Error: ' . mysqli_error($con));
		//}
		
		mysqli_close($con);

		$_SESSION['message'] = "Ditt lösenord har blivit ändrat. Du kan nu logga in.";
		header ("Location: index.php");
	}
	else
	{
		include ("config.php");

		$username = $_POST['username'];
		$resetkey = generateRandomString();
		
		$stmt = $con->prepare('UPDATE `User` SET `ResetKey` =  ? WHERE `Login` = ?');
		$stmt->bind_param('ss', $resetkey, $username);
		$stmt->execute();

		$stmt = $con->prepare('SELECT Name, UserRoleID FROM User WHERE Login = ?');
		$stmt->bind_param('s', $username);
		$stmt->execute();

		$result = $stmt->get_result();

		$count=mysqli_num_rows($result);
		if($count == 1)
		{
			$row = $result->fetch_assoc();
			
			$userrealname = $row['Login'];
			$UserRoleID = $row['UserRoleID'];
		}
		
		
		mysqli_close($con);
		switch($UserRoleID)
		{
			case 1:
			case 2:
				sendNewAccountInfo($username, $userrealname, $resetkey, 1);
				break;
			case 3:
				sendNewAccountInfo($username, $userrealname, $resetkey, 2);
		}
		
		
		$_SESSION['message'] = "Kolla din mail och följ instruktionerna.";
		header ("Location: index.php");
	}
	
	

	
?>